"use client"

import React from 'react'
import { cn } from '@/lib/utils'
import { createSecureLink } from '@/lib/utils/link-security'
import { ACTION_BUTTONS, BOTTOM_NAV_STYLES } from '@/lib/constants/bottom-navigation'
import type { ActionButton, DialogType } from '@/lib/types/bottom-navigation'

interface ActionButtonsProps {
  className?: string
  onDialogOpen?: (dialogType: Exclude<DialogType, null>) => void
  onLinkClick?: (buttonId: string, href: string) => void
}

/**
 * 操作按钮组件
 * 渲染底部的功能按钮（使用方法、打赏、主站、微信、关于我们）
 */
export function ActionButtons({ className, onDialogOpen, onLinkClick }: ActionButtonsProps) {
  // 处理按钮点击事件
  const handleButtonClick = (button: ActionButton, event: React.MouseEvent) => {
    event.preventDefault()

    if (button.type === 'dialog' && button.dialogType) {
      // 弹窗类型按钮
      onDialogOpen?.(button.dialogType)
      
      // 开发环境日志
      if (process.env.NODE_ENV === 'development') {
        console.info('Dialog button clicked:', {
          id: button.id,
          dialogType: button.dialogType
        })
      }
    } else if (button.type === 'link' && button.href) {
      // 链接类型按钮
      const secureLink = createSecureLink(button.href)
      
      // 安全检查
      if (secureLink.onClick && !secureLink.onClick(event.nativeEvent)) {
        return
      }

      // 打开链接
      window.open(button.href, button.target || '_blank')
      
      // 调用回调函数
      onLinkClick?.(button.id, button.href)
      
      // 开发环境日志
      if (process.env.NODE_ENV === 'development') {
        console.info('Link button clicked:', {
          id: button.id,
          href: button.href
        })
      }
    }
  }

  return (
    <div
      className={cn(
        BOTTOM_NAV_STYLES.layout.actionButtons,
        BOTTOM_NAV_STYLES.spacing.buttonGap,
        BOTTOM_NAV_STYLES.spacing.containerPadding,
        'flex-wrap sm:flex-nowrap', // 响应式布局
        className
      )}
      role="toolbar"
      aria-label="网站功能操作"
    >
      {ACTION_BUTTONS.map((button, index) => (
        <ActionButton
          key={button.id}
          button={button}
          onClick={(btn, event) => handleButtonClick(btn, event)}
        />
      ))}
    </div>
  )
}

/**
 * 单个操作按钮组件
 */
interface ActionButtonProps {
  button: ActionButton
  onClick?: (button: ActionButton, event: React.MouseEvent) => void
  className?: string
}

function ActionButton({ button, onClick, className }: ActionButtonProps) {
  const isLink = button.type === 'link'
  
  // 获取按钮图标
  const getButtonIcon = (buttonId: string) => {
    const icons: Record<string, string> = {
      'usage': '❓',
      'payment': '💰',
      'main-site': '🏠',
      'friendLinks': '🔗',
      'about': 'ℹ️'
    }
    return icons[buttonId] || '🔗'
  }

  return (
    <button
      type="button"
      className={cn(
        'inline-flex items-center gap-2',
        'text-sm font-medium',
        'min-w-0 flex-shrink-0', // 防止按钮被压缩
        BOTTOM_NAV_STYLES.colors.buttonDefault,
        BOTTOM_NAV_STYLES.colors.buttonHover,
        BOTTOM_NAV_STYLES.animation.button,
        'rounded-md px-4 py-2',
        'border border-transparent',
        'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
        'hover:border-border',
        'disabled:opacity-50 disabled:cursor-not-allowed',
        className
      )}
      onClick={(event) => onClick?.(button, event)}
      aria-label={`${button.title}${isLink ? ' (在新窗口打开)' : ''}`}
      title={button.title}
    >
      {/* 按钮图标 */}
      <span className="text-base" aria-hidden="true">
        {getButtonIcon(button.id)}
      </span>
      
      {/* 按钮文字 */}
      <span className="whitespace-nowrap">
        {button.title}
      </span>
      
      {/* 外部链接指示器 */}
      {isLink && (
        <svg
          className="w-3 h-3 opacity-60"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
          aria-hidden="true"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
          />
        </svg>
      )}
    </button>
  )
}

/**
 * 响应式操作按钮组件
 * 在移动端显示为垂直布局
 */
interface ResponsiveActionButtonsProps extends ActionButtonsProps {
  variant?: 'horizontal' | 'vertical' | 'auto'
}

export function ResponsiveActionButtons({ 
  variant = 'auto', 
  ...props 
}: ResponsiveActionButtonsProps) {
  const layoutClasses = {
    horizontal: 'flex-row',
    vertical: 'flex-col',
    auto: 'flex-col sm:flex-row'
  }

  return (
    <ActionButtons
      {...props}
      className={cn(
        layoutClasses[variant],
        props.className
      )}
    />
  )
}

export { ActionButton as ActionButtonComponent } 